<template>
	<van-nav-bar title="忘记密码" left-text="" left-arrow @click-left="goBack" />
	<van-form @submit="onSubmit">
		<van-cell-group inset>
			<van-field
				v-model="email"
				name="email"
				label="邮箱"
				placeholder="请输入邮箱"
				:rules="[{ required: true, message: '请填写邮箱' }]"
			/>
			<van-field
				v-model="code"
				center
				clearable
				label="邮箱验证码"
				placeholder="请输入邮箱验证码"
			>
				<template #button>
					<van-button
						size="small"
						type="primary"
						@click="send"
						:disabled="status"
					>
						<span v-show="!status">发送验证码 </span>
						<van-count-down
							style="color: #fff"
							v-show="status"
							ref="countDown"
							:time="60000"
							:auto-start="false"
							:format="format"
							@finish="onFinish"
						/>
					</van-button>
				</template>
			</van-field>
			<van-field
				v-model="password"
				name="password"
				label="重置密码"
				placeholder="请输入密码"
				:rules="[{ required: true, message: '请填写密码' }]"
			/>
		</van-cell-group>
		<div style="margin: 16px">
			<van-button round block type="primary" native-type="submit">
				重置密码
			</van-button>
		</div>
	</van-form>
</template>

<script setup>
	const router = useRouter();
	const route = useRoute();
	let mobile = route.query.mobile;
    let password=ref('')
	const goBack = () => {
		router.push("/business/login");
	};
	const code = ref("");
	const format = ref("ss秒");
	const countDown = ref(null);
	const status = ref(false);
	const email = ref("");
	// 发送邮件
	const send = async () => {
        if (email.value.trim() == "") {
            showFailToast("请输入邮箱");
            return;
        }
		status.value = true;
		countDown.value.start();
		let result = await Api.business.sendByEmail({
			email: email.value
		});
		if (result.code == 1) {
			showSuccessToast(result.msg);
		} else {
			if (result.msg === "已发送验证码，请去邮箱查收") {
				onFinish();
			}
			showFailToast(result.msg);
		}
	};
	// 倒计时结束时触发
	const onFinish = async () => {
		status.value = false;
		countDown.value.reset();
		let result = await Api.business.delmail({
			email: email.value,
		});
		if (result.code == 0) {
			showSuccessToast(result.msg);
		}
	};
	const onSubmit = async () => {
		if (!code.value.trim()) {
			showFailToast("请输入验证码");
			return;
		}
		let result = await Api.business.reset({
			email: email.value,
			code: code.value.trim(),
			password: password.value,
            mobile:mobile
		});
		if (result.code == 1) {
			showSuccessToast({
				message: result.msg,
				onClose: function () {
					router.push("/business/login");
				},
			});
		} else {
			showFailToast(result.msg);
		}
	};
</script>

<style>
</style>